﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;

namespace AddUserAccounts
{
    class MainProgram
    {

        static bool UserExist(string uid, string givenName, string sn)
        {
            int resultCount = 0;
            try
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                using (PrincipalSearcher ps = new PrincipalSearcher())
                {
                    UserPrincipal user = new UserPrincipal(ctx);
                    user.SamAccountName = uid;
                    ps.QueryFilter = user;
                    PrincipalSearchResult<Principal> results = ps.FindAll();
                    resultCount = results.Count<Principal>();
                    results.Dispose();
                    user.Dispose();

                    if (resultCount == 0)
                    {
                        user = new UserPrincipal(ctx);
                        if (givenName.Length != 0)
                        {
                            user.GivenName = givenName;
                        }
                        user.Surname = sn;
                        ps.QueryFilter = user;
                        results = ps.FindAll();
                        resultCount = results.Count<Principal>();
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
            return (resultCount == 0) ? false : true;
        }


        static void CreateUser(string uid, string givenName, string sn, string middleInitial, string emailAddress)
        {
            string name = sn + ", " + givenName;

            try
            {
                PrincipalContext ctx = new PrincipalContext(
                    ContextType.Domain,
                    null,
                    "OU=Migrated,OU=User,DC=c,DC=s,DC=m");

                UserPrincipal user = new UserPrincipal(ctx);

                user.SetPassword("password");

                if (middleInitial.Length > 0)
                {
                    name = sn + ", " + givenName + " " + middleInitial;
                    user.MiddleName = middleInitial;
                }

                if (givenName.Length > 0)
                {
                    user.GivenName = givenName;
                    user.DisplayName = name;
                    user.Name = name;
                }
                else
                {
                    user.DisplayName = sn;
                    user.Name = sn;
                }

                user.Surname = sn;
                user.EmailAddress = emailAddress;
                user.Enabled = true;
                user.ExpirePasswordNow();
                user.SamAccountName = uid;
                user.UserPrincipalName = uid + "@c.s.m";
                user.Save();

            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
        }


        static void Main(string[] args)
        {
            string line;
            if (args.Length != 1)
            {
                Console.Error.WriteLine("usage: AddUserAccounts filename.txt");
                return;
            }

            System.IO.StreamReader sr = new System.IO.StreamReader(args[0]);

            while ((line = sr.ReadLine()) != null)
            {
                String[] tokens = line.Split(new Char[] {';'});
                //0 - Last Name
                //1 - First Name
                //2 - Middle Initial

                Char finitial = tokens[1][0];
                Char linitial = tokens[0][0];

                finitial = Char.ToUpper(finitial);
                linitial = Char.ToUpper(linitial);

                String givenName = finitial + tokens[1].Remove(0, 1);
                String sn = linitial + tokens[0].Remove(0, 1);

                String middleInitial = tokens[2];

                if (middleInitial.Length > 0)
                {
                    if (!Char.IsLetter(middleInitial[0]))
                    {
                        middleInitial = "";
                    }
                }

                String uid = tokens[1][0] + sn;
                String uidm = tokens[1][0] + middleInitial + sn;
                String mail = givenName + middleInitial + sn + "@s.c";

                if (!UserExist(uid, givenName, sn))
                {
                    Console.WriteLine("++ Creating account, {0} {1}...", givenName, sn);
                    CreateUser(uid, givenName, sn, middleInitial, mail);
                    Console.WriteLine("dsquery user -name {0}*", givenName);
                    Console.WriteLine("dsquery user -name {0}*", sn);
                    Console.WriteLine("dsquery user -samid {0}*", uidm);
                   
                }
                else if (!UserExist(uidm, givenName, sn))
                {
                    Console.WriteLine("++ Creating account, {0} {1}...", givenName, sn);
                    //sw.WriteLine("++ Creating account, {0} {1}...", givenName, sn);
                    CreateUser(uid, givenName, sn, middleInitial, mail);
                    Console.WriteLine("dsquery user -name {0}*", givenName);
                    Console.WriteLine("dsquery user -name {0}*", sn);
                    Console.WriteLine("dsquery user -samid {0}*", uidm);
                    
                }
                else
                {
                    Console.WriteLine("-- Account Exists in AD for {0} {1}", givenName, sn);
                    Console.WriteLine("dsquery user -name {0}*", givenName);
                    Console.WriteLine("dsquery user -name {0}*", sn);
                    Console.WriteLine("dsquery user -samid {0}*", uid);
                    //sw.WriteLine("-- Account Exists in AD for {0} {1}", givenName, sn);
                }
            }
        }
    }
}
